import React from 'react';
import PropTypes from 'prop-types';
import { SketchPicker } from 'react-color';
import css from './index.less';
import presetColors from './colors';
import { observer } from 'mobx-react';
import ConfigPortal from 'components/config/portal';


@observer
export default class Color extends React.Component {

  static propTypes = {
    label: PropTypes.any,
    color: PropTypes.string,
    onChange: PropTypes.func,
  };

  static defaultProps = {
    label: '颜色选择',
    color: '#CCC',
    onChange: () => {},
    show: true,
  };

  constructor(props) {
    super(props);
    this.state = {
      portalShow: false,
      historyColor: [], // 存放最近使用的颜色组
    };
  }

  onColorPickerChange(color, event) {
    event.stopPropagation();
    const { onChange } = this.props;
    const { hex, rgb: { r, g, b, a } } = color;
    const rgba = `rgba(${r},${g},${b},${a})`;
    const currentColor = a === 1 ? hex : rgba;
    onChange(currentColor, {
      ...color,
      rgba: rgba,
      string: currentColor,
    });
  }

  render() {

    const { label, color } = this.props;
    const { historyColor } = this.state;

    // 小按钮
    const btnProps = {
      className: css.btn,
      onClick: (e) => {
        if (e && e.nativeEvent) {
          e.nativeEvent.stopImmediatePropagation();
        }
        this.setState({
          portalShow: true
        });
      },
      style: {
        backgroundColor: color,
      }
    };

    // portal层
    const portalProps = {
      className: css.portalPopover,
      isOpen: this.state.portalShow,
      onClose: () => {
        // 把本次选择的颜色添加到历史记录里
        let _historyColor = [];
        if (colors.indexOf(color) === -1) {
          _historyColor.push(color);
        }
        this.setState({
          portalShow: false,
          historyColor: _historyColor.concat(historyColor),
        });
      }
    };

    // 颜色选择器
    const colors = [].concat(presetColors, historyColor);
    const pickerProps = {
      color,
      presetColors: colors,
      onChange: this.onColorPickerChange.bind(this),
    };

    return (
      <div className={css.wrap}>
        <div className={css.label}>{this.props.show ? <span>&bull;&nbsp;</span> : ''}{label}</div>
        <div className={css.block}>
          <div {...btnProps} />
          <ConfigPortal {...portalProps}>
            <SketchPicker {...pickerProps} />
          </ConfigPortal>
        </div>
      </div>
    );
  }
}
